﻿using coremvcdemo.Code;
using coremvcdemo.Controllers;
using coremvcdemo.Dao;
using coremvcdemo.Helper;
using coremvcdemo.Model;
using coremvcdemo.Model.DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Client;
using System.Data;
using System.Numerics;

namespace coremvcdemo.Services.Impl
{
    [Service]
    public class RoleService : IRoleService
    {
        private readonly otherContext dbcontext;

        public RoleService(otherContext dbcontext)
        {
            this.dbcontext = dbcontext;
        }
        /// <summary>
        /// 获取所以角色
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, object> getAllRole()
        {
            var roleList = dbcontext.CoreDemo_B_角色列表.ToList();
            return MyUtils.getSuccessDic(null, roleList);
        }
        /// <summary>
        /// 插入菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="Account"></param>
        /// <returns></returns>
        public Dictionary<string, object> InsertMenu(CoreDemo_B_菜单主表 menu, string Account)
        {
            int MenuId;
            if (dbcontext.CoreDemo_B_菜单主表.Any())
            {
                MenuId = dbcontext.CoreDemo_B_菜单主表.Max(c => c.MenuId) + 1;
            }
            else
            {
                MenuId = 1;
            }
            menu.MenuId = MenuId;
            menu.EditCard = Account;
            dbcontext.CoreDemo_B_菜单主表.Add(menu);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("新增成功");
            }
            else
            {
                return MyUtils.getFailDic("新增失败");
            }
        }
        /// <summary>
        /// 查询菜单
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Dictionary<string, object> FindMenu()
        {
            var menuList = dbcontext.CoreDemo_B_菜单主表.OrderBy(j => j.Sort);
            return MyUtils.getSuccessDic(null, menuList);
        }

        public Dictionary<string, object> DeleteMenu(CoreDemo_B_菜单主表 menu)
        {
            dbcontext.CoreDemo_B_菜单主表.Remove(menu);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> UpdateMenu(CoreDemo_B_菜单主表 menu, string Account)
        {
            menu.EditCard = Account;
            dbcontext.CoreDemo_B_菜单主表.Update(menu);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> InsertRole(RoleMenu roleMenu, string Account)
        {
            var role = roleMenu.roleList.First();
            role.ID = Guid.NewGuid().ToString();
            role.ControlType = "全部";
            role.EditCard = Account;
            role.EditTime = DateTime.Now;
            var menuArry = Array.ConvertAll(roleMenu.MenuList.ToArray(), new Converter<int, string>(a => Convert.ToString(a)));
            role.RolePower = string.Join(",", menuArry);
            dbcontext.Add(role);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> GetRoleInfo(string Id)
        {
            var role = dbcontext.CoreDemo_B_角色列表.Single(j => j.ID == Id);
            return MyUtils.getSuccessDic(null, role);
        }

        public Dictionary<string, object> DeleteRole(CoreDemo_B_角色列表 role)
        {
            dbcontext.CoreDemo_B_角色列表.Remove(role);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> GetAllPower()
        {
            var powerList = dbcontext.CoreDemo_B_人员权限;
            return MyUtils.getSuccessDic(null, powerList);
        }

        public Dictionary<string, object> GetAllUsing()
        {
            var UserList = dbcontext.DB_VB_教工信息.OrderBy(j => j.顺序 == null ? int.MaxValue : j.顺序).Select(j => new
            {
                ID = j.ID,
                cardNum = j.卡号,
                Campus = j.校区,
                Name = j.姓名,
                Sex = j.性别,
                Phone = j.移动电话,
                DepartName = j.部门,
                Employment = j.用工性质,
                UseStatus = j.使用状态
            });
            return MyUtils.getSuccessDic(null, UserList);
        }
        public Dictionary<string, object> GetDeptUsing()
        {
            var DeptList = dbcontext.DB_VB_教工信息.Select(j => new
            {
                DepartName = j.部门,
            }).Distinct();
            return MyUtils.getSuccessDic(null, DeptList);
        }

        public Dictionary<string, object> GetUserByDeptAndCardNum(PowerAddPara para)
        {
            var UserList = dbcontext.DB_VB_教工信息.Select(j => new
            {
                ID = j.ID,
                cardNum = j.卡号,
                Campus = j.校区,
                Name = j.姓名,
                Sex = j.性别,
                Phone = j.移动电话,
                DepartName = j.部门,
                Employment = j.用工性质,
                UseStatus = j.使用状态,
                Sort = j.顺序 == null ? int.MaxValue : j.顺序
            });
            if (!string.IsNullOrEmpty(para.serName))
            {
                UserList = UserList.Where(u => u.cardNum == para.serName);
            }
            if (!string.IsNullOrEmpty(para.deptName))
            {
                UserList = UserList.Where(u => u.DepartName == para.deptName);
            }
            UserList.OrderBy(u => u.Sort);
            return MyUtils.getSuccessDic(null, UserList);
        }

        public Dictionary<string, object> SetRole(PowerAddModel model, string Account)
        {
            List<CoreDemo_B_人员权限> powerList = new List<CoreDemo_B_人员权限>();
            model.CardList.ForEach(c =>
            {
                var power = new CoreDemo_B_人员权限();
                var teacher = dbcontext.DB_VB_教工信息.Single(t => t.卡号 == c);
                power.ID = Guid.NewGuid().ToString();
                power.TeacherId = teacher.ID;
                power.Card = c;
                power.Name = teacher.姓名;
                power.RoleName = model.RoleName;
                power.Role = model.RoleId;
                power.EditTime = DateTime.Now;
                power.EditCard = Account;
                powerList.Add(power);
            });
            var oriCount = dbcontext.CoreDemo_B_人员权限.Count();
            dbcontext.BulkInsert(powerList);
            var newCount = dbcontext.CoreDemo_B_人员权限.Count();
            if (oriCount != newCount)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> deletePower(CoreDemo_B_人员权限 model)
        {
            dbcontext.CoreDemo_B_人员权限.Remove(model);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public Dictionary<string, object> GetPowerInfoByParam(string Card, string Name)
        {
            IQueryable<CoreDemo_B_人员权限> powerList = dbcontext.CoreDemo_B_人员权限;
            if (!string.IsNullOrEmpty(Card))
            {
                powerList = powerList.Where(p => p.Card == Card);
            }
            if (!string.IsNullOrEmpty(Name))
            {
                powerList = powerList.Where(p => p.Name == Name);
            }
            return MyUtils.getSuccessDic(null, powerList);
        }

        public Dictionary<string, object> UpdateRole(RoleMenu roleMenu, string Account)
        {
            var role = roleMenu.roleList.First();
            role.ID = roleMenu.Id;
            role.ControlType = "全部";
            role.EditCard = Account;
            role.EditTime = DateTime.Now;
            var menuArry = Array.ConvertAll(roleMenu.MenuList.ToArray(), new Converter<int, string>(a => Convert.ToString(a)));
            role.RolePower = string.Join(",", menuArry);
            dbcontext.Update(role);
            if (dbcontext.SaveChanges() != 0)
            {
                return MyUtils.getSuccessDic("操作成功");
            }
            else
            {
                return MyUtils.getFailDic("操作失败");
            }
        }

        public async Task<Dictionary<string, object>> GetPersonMenu(string Account)
        {
            var powerList = dbcontext.CoreDemo_B_人员权限.Where(p => p.Card == Account).Select(p => new { roleId = p.Role }).Distinct();
            List<string> list = new List<string>();
            await powerList.ForEachAsync(r =>
            {
                list.Add(r.roleId);
            });
            var menuList = dbcontext.CoreDemo_B_角色列表.Where(r => list.Contains(r.ID)).Select(r => new
            {
                menus = r.RolePower
            }).Distinct();
            string menustr = "";
            await menuList.ForEachAsync(m =>
            {
                menustr += m.menus;
            });
            list = menustr.Split(',').Distinct().ToList();
            var parentMenus = dbcontext.CoreDemo_B_菜单主表.Where(m => list.Contains(m.MenuId.ToString()) && m.FatherId == 0);
            var childrenMenus = dbcontext.CoreDemo_B_菜单主表.Where(m => list.Contains(m.MenuId.ToString()) && m.FatherId != 0);
            List<PersionMenu> menus = new List<PersionMenu>();
            await parentMenus.ForEachAsync(p =>
            {
                PersionMenu menu = new PersionMenu();
                menu.FatherId = p.FatherId;
                menu.Href = p.Href;
                menu.MenuName = p.MenuName;
                menu.MenuId = p.MenuId;
                List<PersionMenu> childrens = new List<PersionMenu>();
                var childrenList = childrenMenus.Where(c => c.FatherId == p.MenuId);
                foreach(var c in childrenList)
                {
                    PersionMenu children = new PersionMenu();
                    children.FatherId = c.FatherId;
                    children.Href = c.Href;
                    children.MenuName = c.MenuName;
                    children.MenuId = c.MenuId;
                    childrens.Add(children);
                }
                menu.children = childrens;
                menus.Add(menu);
            });
            return MyUtils.getSuccessDic(null, menus);

        }
    }
}
